package com.mavenq.fly.business.controller;

import com.mavenq.fly.business.service.MinioUtils;
import com.mavenq.fly.config.MinioProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
@Slf4j
@RequestMapping(value = "minio")
public class MinioController {

    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private MinioProperties minioProperties;

    @PostMapping(value = "upload")
    public Object upload(@RequestParam("file")MultipartFile file, @RequestParam(required = false) String name) {
        String objectName = minioUtils.putObject(name, file);
        System.out.println("上传成功");
        String objectURL = minioUtils.getObjectURL(minioProperties.getBucket(), objectName);
        return objectURL;
    }


    @GetMapping("/downloadFile")
    private void downloadFile(HttpServletResponse response, String filename) throws IOException {

        InputStream inputStream = minioUtils.getObject(minioProperties.getBucket(), filename);
        // 设置 Content-Type 和 Header 信息
        response.setContentType("image/jpeg");
        //response.setHeader("content-disposition", "attachment;fileName=" + filename+".png");

        // 将 InputStream 的内容写入到响应中
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, bytesRead);
        }
        // 关闭流
        inputStream.close();
    }


}
